package com.fafa.swing.base;

import javax.swing.*;
import java.awt.*;

/**
 * @author : fafa
 * @version V1.0
 * @Project: SwingTest
 * @Package com.fafa.swing
 * @Description: 网格包布局管理器
 * @date Date : 2019年11月23日 11:32
 */
public class GridBagLayoutDemo extends JFrame {

    /**
     * 向JFrame中添加JButton按钮
     * @param title
     * @param jFrame
     * @param gridBagLayout
     * @param gridBagConstraints
     */
    public static void makeButton(String title, JFrame jFrame, GridBagLayout gridBagLayout,
                                  GridBagConstraints gridBagConstraints){
        JButton jButton = new JButton(title);
        gridBagLayout.setConstraints(jButton,gridBagConstraints);
        jFrame.add(jButton);
    }


    public static void main(String[] args) {
        JFrame jFrame = new JFrame("拨号盘");
        GridBagLayout gridBagLayout = new GridBagLayout();
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        jFrame.setLayout(gridBagLayout);
        gridBagConstraints.fill = GridBagConstraints.BOTH;  //组件填充显示区域
        gridBagConstraints.weightx = 0.0;
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;    //结束行
        JTextField jTextField = new JTextField("1234567890");
        gridBagLayout.setConstraints(jTextField,gridBagConstraints);
        jFrame.add(jTextField);
        gridBagConstraints.weightx=0.5; // 指定组件的分配区域
        gridBagConstraints.weighty=0.2;
        gridBagConstraints.gridwidth=1;

        makeButton("7",jFrame,gridBagLayout,gridBagConstraints);
        makeButton("8",jFrame,gridBagLayout,gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        makeButton("9",jFrame,gridBagLayout,gridBagConstraints);
        gridBagConstraints.gridwidth=1;    //重新设置gridwidth的值

        makeButton("4",jFrame,gridBagLayout,gridBagConstraints);
        makeButton("5",jFrame,gridBagLayout,gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        makeButton("6",jFrame,gridBagLayout,gridBagConstraints);
        gridBagConstraints.gridwidth=1;    //重新设置gridwidth的值

        makeButton("1",jFrame,gridBagLayout,gridBagConstraints);
        makeButton("2",jFrame,gridBagLayout,gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        makeButton("3",jFrame,gridBagLayout,gridBagConstraints);
        gridBagConstraints.gridwidth=1;    //重新设置gridwidth的值

        makeButton("返回",jFrame,gridBagLayout,gridBagConstraints);
        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        makeButton("确认",jFrame,gridBagLayout,gridBagConstraints);
        gridBagConstraints.gridwidth = 1;

        gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
        makeButton("OK",jFrame,gridBagLayout,gridBagConstraints);


        jFrame.setVisible(true);
        jFrame.setBounds(400,400,400,400);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
